package com.travel.config;

import com.travel.entity.po.User;
import com.travel.interceptor.UserContextInterceptor;
import com.travel.utils.JWTUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class WebConfig implements WebMvcConfigurer {

//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        registry.addMapping("/**")
//                .allowedOriginPatterns("*")
//                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
//                .allowedHeaders("*")
//                .exposedHeaders("Authorization")
//                .allowCredentials(true)
//                .maxAge(3600);
//    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册管理员拦截器
        registry.addInterceptor(new AdminInterceptor())
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin/login");
                
        // 注册用户上下文拦截器，应用于所有请求
        registry.addInterceptor(new UserContextInterceptor())
                .addPathPatterns("/**");
    }


    class AdminInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
            Cookie[] cookies = request.getCookies();
            if (cookies == null) {return false;}
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())){
                    if (JWTUtil.validateToken(cookie.getValue())){
                        User user = JWTUtil.getUser(cookie.getValue());
                        return user.getUserStatus() == 0;
                    }
                    return false;
                }
            }
            return false;
        }
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 添加对/images/**路径的静态资源映射
        registry.addResourceHandler("/images/**")
                .addResourceLocations("file:src/main/resources/static/images/")
                .setCachePeriod(3600)
                .resourceChain(true);
                
        // 添加favicon.ico映射
        registry.addResourceHandler("favicon.ico")
                .addResourceLocations("classpath:/static/")
                .setCachePeriod(3600);
    }

}
